﻿using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Windows.Media.Imaging;

namespace SSG.Tools
{
    /// <summary>
    /// Tools for WPF, e.g. image conversion.
    /// </summary>
    public static class WpfTools
    {
        /// <summary>
        /// Convert Bitmap to BitmapImage.
        /// </summary>
        /// <param name="bitmap"></param>
        /// <returns></returns>
        // http://stackoverflow.com/questions/5346727/convert-memory-stream-to-bitmapimage
        // http://stackoverflow.com/questions/6484357/converting-bitmapimage-to-bitmap-and-vice-versa
        public static BitmapImage Bitmap2BitmapImage(this Bitmap bitmap)
        {
            if (bitmap == null) return null;
            using (MemoryStream ms = new MemoryStream()) {
                bitmap.Save(ms, ImageFormat.Png);
                BitmapImage bitmapImage = new BitmapImage();
                bitmapImage.BeginInit();
                bitmapImage.StreamSource = ms;
                bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
                bitmapImage.EndInit();
                bitmapImage.Freeze();
                return bitmapImage;
            }
        }
    }
}